import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-07-26
 * Time: 9:10
 */
public class Heap {
    public int[] elem;
    public int usedSize;
    public Heap(){
        this.elem = new int[10]; //默认开10个空间
    }
    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = i;
            usedSize++;
        }
    }
    public void creatHeap(){    //用向下调整算法创建大根堆
        init(elem);
        for(int i = (elem.length - 1 - 1) / 2; i >= 0; i--){
            siftDown(i, usedSize);
        }
    }
    private void siftDown(int parent, int usedSize){
        int child = 2 * parent + 1;
        while(child < usedSize){
            if(child + 1 < usedSize && elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[parent] < elem[child]){
                swap(elem, parent, child);
                parent = child;
                child = 2 * parent + 1;
            }else{
                break;
            }
        }
    }
    private void swap(int[] elem, int i, int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem, 2 * usedSize + 1);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize - 1);
    }

    private void siftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0){
            if(elem[parent] < elem[child]){
                swap(elem, parent, child);
                child = parent;
                parent = (child - 1) / 2;
            }else{
                break;
            }
        }
    }

    public boolean isFull(){
        return elem.length == usedSize;
    }
    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int ret = elem[0];
        swap(elem, 0, usedSize - 1);
        usedSize--;
        siftDown(0, usedSize);
        return ret;
    }
    public boolean isEmpty(){
        return usedSize == 0;
    }
    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }
}
